<template>
    <div class="url-to-base">
        <div class="box">
            <h3>nomarl</h3>
            <img v-images.url1="urls" :src="url1" alt="" class="box-img" />
        </div>
        <div class="box">
            <h3>urlToBase64</h3>
            <img :src="url2" alt="" class="box-img" />
        </div>
    </div>
</template>
<script setup>
import test1 from '@/assets/images/test1.png'
import { onMounted, ref } from 'vue'
const url1 = ref(test1)
const url2 = ref('')
const urls = ref([])
console.log('import', import.meta)
onMounted(() => {
    urlToBase64(
        new URL('@/assets/images/test2.png', import.meta.url),
        (url) => {
            url2.value = url
            urls.value = [url1.value, url2.value]
        }
    )
})
const urlToBase64 = (url, cb) => {
    return new Promise((resolve, reject) => {
        // 1、创建 ctx 画布
        const canvas = document.createElement('canvas')
        const ctx = canvas.getContext('2d')
        // 2、创建 Image 对象
        const image = new Image()
        // 3、给 img 对象赋值 src 并监听 onload 事件
        image.src = url
        image.onload = () => {
            // 4、将图片绘制到画布上
            canvas.width = image.width
            canvas.height = image.height
            ctx.drawImage(image, 0, 0)
            // 5、使用 toDataURL 方法将画布转换为 base64
            const dataURL = canvas.toDataURL()
            cb && cb(dataURL)
            resolve(dataURL)
        }
    })
}
</script>
<style lang="scss" scoped>
.url-to-base {
    color: black;
    display: flex;
    justify-content: space-around;
    .box {
        width: 40%;
        .box-img {
            width: 100%;
            margin-top: 20px;
        }
    }
}
</style>
